import Taro from "@tarojs/taro";
import useAppContext from "@/hooks/useAppContext";
import { useForm } from "rc-field-form";
import { useEffect } from "react";
import { useRequest } from "ahooks";
import { fetchUpdateUserInfo } from "./service";
import { UserInfo } from "@/service/type";
import useAppAction from "@/hooks/useAppAction";
import useDictionaries from "@/hooks/useDictionaries";

interface FormData {
  /**头像 */
  headImg: string;
  /**微信号 */
  nickName: string;
  /**生日 */
  birthday: string,
  /**生肖 */
  chineseZodiac: string,
  /**星座 */
  constellation: string,
  /**学历 */
  education: string,
  /**学历证件号 */
  educationCertificateNo: string,
  /**身高 */
  height: number,
  /**婚史 */
  marriageHistory: string,
  /**民族 */
  nation: string,
  nationCn: string,
  /**籍贯 */
  nativePlace: string,
  /**现住地区 */
  residence: string,
  /**体重 */
  weight: number,
  /**性别 */
  gender: '1' | '2'
}

type KeyType = keyof FormData
type ValueType = FormData[keyof FormData]

function useData() {
  const userInfo = useAppContext(state => state.userInfo)
  const refresh = useAppAction((action) => action.refresh)
  const selectorNameWithDictionaries = useDictionaries()
  const [form] = useForm<FormData>();
  const { run: updateUserInfo } = useRequest((options: Partial<UserInfo>) => fetchUpdateUserInfo(options), {
    manual: true,
    onSuccess() {
      Taro.showToast({ icon: 'none', title: '修改成功' })
      refresh()
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }
  })


  /**picker设置值 */
  const onSetFieldValue = (key: KeyType, value: ValueType, label?: string) => {
    const params = form.getFieldsValue()
    form.setFieldsValue({
      ...params,
      [key]: value,
      [key + 'Cn']: label
    })
  }

  /**提交表单 */
  const onSubmit = () => {
    const { nickName, headImg, gender, ...reset } = form.getFieldsValue();
    updateUserInfo({
      // ...userInfo,
      nickName,
      headImg,
      gender,
      customerBasicInfo: {
        ...userInfo.customerBasicInfo,
        ...reset,
      }
    })
  };

  /**跳过 */
  const onNext = () => {
    Taro.showModal({
      content: "个人中心页可继续完善信息",
      confirmColor: "#FD486E",
      success: (e) => {
        if (e.confirm) {
          Taro.reLaunch({
            url: "/pages/index/index",
          });
        }
      },
    });
  };

  return {
    userInfo: userInfo,
    form,
    selectorNameWithDictionaries,
    onSetFieldValue,
    onSubmit,
    onNext
  }
}

export default useData